package com.tom.mybatis.executor;

import com.tom.mybatis.config.Configuration;
import com.tom.mybatis.config.MapperRegistory;
import com.tom.mybatis.statement.StatementHandler;

import javax.naming.ldap.ControlFactory;
import java.util.HashMap;
import java.util.Map;

/**
 * @author : tom
 * @project: tom-mybatis
 * @date : 2018/11/7 15:03
 */
public class CachingExecutor implements Executor {

    private Configuration configuration;

    private SimpleExecutor delegate;

    private Map<String,Object> localCache=new HashMap<String, Object>();

    public CachingExecutor(SimpleExecutor delegate) {
        this.delegate = delegate;
    }

    public CachingExecutor(Configuration configuration) {
        this.configuration = configuration;
    }


    public <T> T query(MapperRegistory.MapperDate mapperData, Object parameter) throws Exception {
        StatementHandler handler = new StatementHandler(configuration);
        Object result = localCache.get(mapperData.getSql());
        if( null != result){
            System.out.println("缓存命中");
            return (T)result;
        }
        result =  (T) delegate.query(mapperData,parameter);
        localCache.put(mapperData.getSql(),result);
        return (T)result;
    }
}
